package com.dk.controller;


import com.dk.pojo.TbCars;
import com.dk.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@RestController
@RequestMapping("ess")
@Api
@ApiOperation("千人千面")
public class ESController {

    @Autowired
    private RestHighLevelClient client;



    @PostMapping("getLabel")
    @ApiOperation(value = "获取推荐的车辆")
    @ApiImplicitParam(name = "range", value = "要查询的条件", required = true, paramType = "query")
    public Result<List> getLabel(@RequestParam Set<String> range) {
        try {
            List list = new ArrayList<>();
            // 搜索请求对象
            SearchRequest searchRequest = new SearchRequest("huasheng");
            //搜索元构建对象
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //进行搜索条件的设置
            searchSourceBuilder.query(xbLabelBoolQuery(range));//把条件抽取出来了
            //searchSourceBuilder.query(QueryBuilders.wildcardQuery("name","大"));
            searchRequest.source(searchSourceBuilder);
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);


            SearchHits hits = response.getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getId());
                list.add(hit);
            }

            return Result.OK().setData(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ER();
    }

    //根据课程标签搜索的条件的抽取
    public BoolQueryBuilder xbLabelBoolQuery(Set<String> range) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        for (String id : range) {
            boolQuery.should(QueryBuilders.matchQuery("tag_id1", id));
            boolQuery.should(QueryBuilders.matchQuery("tag_id2", id));
            boolQuery.should(QueryBuilders.matchQuery("tag_id3", id));
        }
        return boolQuery;
    }

}
